<template>
  <div class="common-container">
    <div class="header">
      <div class="header_left">
        <el-input
          placeholder="请输入巡查项"
          v-model="searchForm.name"
          style="width: 300px; margin-right: 15px"
          size="small"
          maxlength="20"
          clearable
          @clear="clearInput"
          class="el_input"
        >
          <el-button
            slot="append"
            :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'"
            @click="searchClick"
          >
          </el-button>
        </el-input>
      </div>
      <div class="header_right">
        <el-button
          class="el_button"
          size="small"
          icon="el-icon-plus"
          @click="addClick"
        >
          新增
        </el-button>
        <el-button
          class="el_button"
          size="small"
          icon="el-icon-bottom"
          type="info"
          style="margin-left: 15px"
          @click="onStateBatch"
        >
          导出
        </el-button>
      </div>
    </div>
    <div class="content">
      <div class="patrol-list" style="height: calc(100% - 65px)">
        <div
          class="patrol-list__item"
          :class="item.isOpen ? 'isOpen' : ''"
          v-for="(item, index) in dataList"
          :key="item.id"
        >
          <div class="patrol-Item-title">
            <span class="patrol-Item-name" v-if="!item.isEdit">{{
              item.name
            }}</span>
            <el-input
              placeholder="请输入巡查项分类"
              v-model="patrolForm.name"
              style="width: 300px; margin-right: 15px"
              size="small"
              maxlength="30"
              clearable
              class="el_input"
              v-else
            >
            </el-input>
            <div class="operate-list flex flex-ai-c">
              <el-tooltip
                content="编辑"
                class="operate-item act-btn"
                v-if="!item.isEdit"
              >
                <i class="el-icon-edit" @click="onEdit(item)"></i>
              </el-tooltip>
              <el-tooltip
                content="删除"
                class="operate-item act-btn"
                v-if="!item.isEdit"
              >
                <i class="el-icon-delete" @click="onDel(item)"></i
              ></el-tooltip>
              <el-tooltip
                content="新增"
                class="operate-item act-btn"
                v-if="item.isEdit"
              >
                <i class="el-icon-plus" @click="onAdd(item)"></i>
              </el-tooltip>
              <el-tooltip content="保存" class="operate-item act-btn">
                <i
                  class="el-icon-check"
                  v-if="item.isEdit"
                  @click="onSave(item, index)"
                ></i
              ></el-tooltip>
              <el-tooltip content="取消" class="operate-item act-btn">
                <i
                  class="el-icon-close"
                  v-if="item.isEdit"
                  @click="onCancel()"
                ></i
              ></el-tooltip>
              <div class="operate-item act-btn" style="margin-left: 16px">
                <div @click="onExpend(item)">
                  <i class="el-icon-arrow-down arrow" v-if="!item.isOpen"></i>
                  <i class="el-icon-arrow-up arrow" v-else></i>
                </div>
              </div>
            </div>
          </div>
          <div class="patrol-content-list" v-if="item.isOpen">
            <el-form
              :model="patrolForm"
              ref="refPatrolForm"
              label-width="110px"
              style="margin: 0px 8px"
            >
              <div
                v-for="(item2, index2) in patrolForm.patrolCategorys"
                :key="item2.id"
                class="conditions"
              >
                <el-form-item
                  size="small"
                  :label="'巡查项' + (index2 + 1)"
                  class="patrol-content-item"
                  :prop="`patrolCategorys[${index2}].content`"
                  :rules="[
                    {
                      required: true,
                      message: '请输入巡查项',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-input
                    placeholder="请输入巡查项"
                    v-model="patrolForm.patrolCategorys[index2].content"
                    style="width: 95%; margin-right: 15px"
                    size="small"
                    maxlength="30"
                    clearable
                    class="el_input"
                    :readonly="!item.isEdit"
                  >
                  </el-input>
                  <el-tooltip content="删除">
                    <i
                      class="el-icon-delete"
                      @click="onRemove(item, index, item2, index2)"
                      :style="{
                        cursor:
                          patrolForm.patrolCategorys.length == 1 || !item.isEdit
                            ? 'not-allowed'
                            : 'pointer',
                      }"
                    ></i>
                  </el-tooltip>
                </el-form-item>
              </div>
            </el-form>
          </div>
        </div>
      </div>
      <pagination
        :total="total"
        :page.sync="page"
        :limit.sync="limit"
        :pageSizes="[10, 20, 30, 50]"
        @pagination="getDataList"
        class="pagination"
      />
    </div>
  </div>
</template>
<script>
import {
  reqPatrolItemPage,
  reqPatrolItemUpdate,
  reqPatrolItemAdd,
  reqPatrolCategoryDel,
  reqPatrolItemDel,
} from "@api/patrol.js";
import Pagination from "@components/Pagination.vue";
import tableStyleMixin from "@mixin/table-style";
import { mapState } from "vuex";
export default {
  data() {
    return {
      searchForm: {
        name: "",
        content: "",
      },
      patrolForm: {
        name: "",
        patrolCategorys: [],
      },
      page: 1,
      limit: 10,
      total: 0,
      loadingSearch: false,
      dataList: [],
      isAdd: false,
    };
  },
  components: { Pagination },
  mixins: [tableStyleMixin],
  computed: {
    ...mapState(["user"]),
  },
  mounted() {
    this.getDataList();
  },
  methods: {
    // 搜索
    async searchClick() {
      this.page = 1;
      this.limit = 10;
      this.loadingSearch = true;
      await this.getDataList();
      this.loadingSearch = false;
    },

    // 清空搜索框
    clearInput() {
      this.page = 1;
      this.getDataList();
    },
    // 新增
    addClick() {
      if (this.dataList.filter((item) => item.isEdit).length > 0)
        return this.$modal.notifyWarning("请先保存巡查项分类");
      this.dataList.forEach((item) => {
        item.isOpen = false;
      });
      this.isAdd = true;
      this.patrolForm = {
        name: "",
        patrolCategorys: [],
      };
      this.patrolForm.patrolCategorys.push({
        content: "",
        id: new Date().getTime(),
        sort: this.patrolForm.patrolCategorys.length + 1,
      });
      this.dataList.unshift({
        name: "",
        id: new Date().getTime(),
        isEdit: true,
        isOpen: true,
      });
    },
    // 导出
    async onStateBatch() {},
    // 获取列表
    async getDataList() {
      // this.searchForm.tenantId = this.user.tenantId;
      // this.searchForm.orgId = this.searchForm.orgId;
      // this.searchForm.unitId = this.searchForm.unitId;
      // this.searchForm.userId = this.user.userId;
      const res = await reqPatrolItemPage(
        this.page,
        this.limit,
        this.searchForm
      );
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let { rows, total } = res.data;
      rows.forEach((item) => {
        item.isOpen = false;
        item.isEdit = false;
      });
      this.dataList = rows;
      this.total = total;
      this.patrolForm = {
        name: "",
        patrolCategorys: [],
      };
    },
    // 展开/收起
    onExpend(data) {
      if (this.dataList.filter((item) => item.isEdit).length > 0)
        return this.$modal.notifyWarning("请先保存巡查项分类");
      this.patrolForm.name = "";
      this.patrolForm.patrolCategorys = {};
      this.dataList.forEach((item) => {
        if (item.id == data.id) {
          if (item.fireFacilityId) {
            this.patrolForm.name = item.name;
            this.patrolForm.patrolCategorys = item.patrolCategorys;
          }
          if (item.isOpen && item.isEdit)
            return this.$modal.notifyWarning("请先保存巡查项分类");
          item.isOpen = !item.isOpen;
        } else {
          item.isOpen = false;
        }
      });
    },
    // 编辑
    onEdit(data) {
      if (this.dataList.filter((item) => item.isEdit).length > 0)
        return this.$modal.notifyWarning("请先保存巡查项分类");
      this.patrolForm.name = "";
      this.patrolForm.patrolCategorys = {};
      this.dataList.forEach((item) => {
        if (item.id == data.id) {
          if (item.fireFacilityId) {
            this.patrolForm.name = item.name;
            this.patrolForm.patrolCategorys = item.patrolCategorys;
          }
          item.isEdit = true;
          item.isOpen = true;
        } else {
          item.isEdit = false;
          item.isOpen = false;
        }
      });
    },
    onAdd() {
      this.patrolForm.patrolCategorys.push({
        content: "",
        id: new Date().getTime(),
        sort: this.patrolForm.patrolCategorys.length + 1,
      });
    },
    // 删除巡查项
    async onDel(data) {
      const result = await this.$confirm("确定删除所选项吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {});
      if (result !== "confirm") return;
      let res = await reqPatrolItemDel(data.id);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.page = 1;
      await this.getDataList();
      this.$modal.notifySuccess("操作成功");
    },
    onSave(data, index) {
      if (!this.patrolForm.name)
        return this.$modal.notifyWarning("请输入巡查项分类名称");
      console.log(this.$refs.refPatrolForm, "this.$refs.refPatrolForm");
      this.$refs.refPatrolForm[0].validate(async (valid) => {
        if (valid) {
          let currentItem = this.dataList.filter((item) => item.id == data.id);
          console.log(currentItem, "currentItem");
          let res;
          let patrolForm_copy = JSON.parse(JSON.stringify(this.patrolForm));
          if (currentItem.length && currentItem[0].fireFacilityId) {
            patrolForm_copy.fireFacilityId = currentItem[0].fireFacilityId;
            patrolForm_copy.patrolCategorys.forEach((item) => {
              if (!item.createTime) delete item.id;
            });
            res = await reqPatrolItemUpdate(currentItem[0].id, patrolForm_copy);
          } else {
            res = await reqPatrolItemAdd(patrolForm_copy);
          }
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.page = 1;
          await this.getDataList();
          this.$modal.notifySuccess("操作成功");
        }
      });
    },
    async onCancel() {
      // if (this.isAdd) {
      //   this.dataList.splice(0, 1);
      //   this.isAdd = false;
      // } else {
      //   this.dataList.forEach((item) => {
      //     item.isEdit = false;
      //     item.isOpen = false;
      //   });
      // }
      this.page = 1;
      await this.getDataList();
    },
    async onRemove(data, index, data2, index2) {
      if (!data.isEdit) return;
      this.dataList[index].patrolCategorys.splice(index2, 1);
    },
    // 改变页码时触发
    onPageChange(e) {
      // 计算当前页的数据范围
      // const start = (e - 1) * 10;
      // const end = start + 10;
      // data.value = data_copy_all.value.slice(start, end);
      // pageOptions.value.total = data_copy_all.value.length;
    },
  },
};
</script>

<style scoped lang="less">
@import url("~@views/style/tablePage.less");
@import url("./inspItems.less");
</style>
